package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.core.listenter.ExcelDictDTOListener;
import com.atguigu.srb.core.pojo.DTO.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author ZLHao
 * @since 2021-07-12
 */
@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {


    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * @description: 开始读数据
     * @param: inputStream
     * @return: void
     * @author Administrator
     * @date: 2021/7/15 0015 13:48
     */

    @Transactional(rollbackFor = Exception.class)  //出现任何错误就回滚
    @Override
    public void importData(InputStream inputStream) {

        // 开始读数据
        EasyExcel.read(inputStream, ExcelDictDTO.class, new ExcelDictDTOListener(baseMapper)).sheet().doRead();
        log.info("读取数据成功");
    }

    /**
     * @description: 取出字典所有数据   导出数据excel
     * @param:
     * @return: java.util.List<com.atguigu.srb.core.pojo.DTO.ExcelDictDTO>
     * @author Administrator
     * @date: 2021/7/15 0015 22:33
     */
    @Override
    public List<ExcelDictDTO> listDictData() {

        List<Dict> dictList = baseMapper.selectList(null);
        System.out.println("取出的字典大小是："+dictList.size());
        //创建ExcelDictDTO列表，将Dict列表转换成ExcelDictDTO列表
        // 将某一个bean转换成另一个bean对象
        ArrayList<ExcelDictDTO> excelDictDTOS = new ArrayList<>();
        for (Dict dict : dictList) {
            ExcelDictDTO excelDictDTO = new ExcelDictDTO();
            // 将一个bean里面 的 同名属性转换到另一个bean里面
            BeanUtils.copyProperties(dict,excelDictDTO);
            excelDictDTOS.add(excelDictDTO);
        }
        return excelDictDTOS;
    }


    /**
     * @description: 展示数据字典
     *
     *
     *
     * @param: parentId
     * @return: java.util.List<com.atguigu.srb.core.pojo.entity.Dict>
     * @author Administrator
     * @date: 2021/7/15 0015 20:50
     */
    @Override
    public List<Dict> listByParentId(Long parentId) {
        List<Dict> dictList = null;
        try {
            // 1.  首先，先去redis进行查询，看是否存在传入的id的字典值


            dictList  =(List<Dict>) redisTemplate.opsForValue().get("srb:core:distList:" + parentId);
            // 如果dictList 不为空，说明redis中有数据
            if (dictList != null){
                // 2. 如果有，直接返回数据
                log.info("redis中拿的数据");
                return  dictList;
            }
        } catch (Exception e) { // 如果redis服务器有异常，没有取出数据
            log.info("redis服务器异常"); // 继续执行后面的，也就是从数据库中拿
        }

        // 3. 没有则从数据库中取出返回，并放入redis



        // 根据id取出值
        QueryWrapper<Dict> queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id",parentId);
        List<Dict> dicts = baseMapper.selectList(queryWrapper);

        // 设置孩子节点的状态
        for (Dict dict : dicts) {
            // 先判断当前的id是否还有孩子
             dict.setHasChildren(hasChildren(dict.getId()));
        }
        // 将取出的数据放入redis，放入redis时也会出现问题,如redis没有开
        try {
            redisTemplate.opsForValue().set("srb:core:distList:" + parentId,dicts,5, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.info("redis服务器异常");
        }
        log.info("数据库中拿的数据");
        return dicts;
    }

    /**
     * @description: 判断取出的字典是否是有孩子节点
     * @param: id
     * @return: boolean
     * @author Administrator
     * @date: 2021/7/15 0015 22:33
     */
    private  boolean hasChildren(Long id){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id",id);
        List<Dict> dicts = baseMapper.selectList(queryWrapper);
        if (dicts.size()>0){  //说明有孩子节点
            return true;
        }
        return  false;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {

        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(queryWrapper);
        System.out.println(dict);

        return  this.listByParentId(dict.getId());
    }

    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, Integer value) {
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<Dict>();
        dictQueryWrapper.eq("dict_code", dictCode);
        Dict parentDict = baseMapper.selectOne(dictQueryWrapper);

        if(parentDict == null) {
            return "";
        }

        dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper
                .eq("parent_id", parentDict.getId())
                .eq("value", value);
        Dict dict = baseMapper.selectOne(dictQueryWrapper);

        if(dict == null) {
            return "";
        }

        return dict.getName();
    }
}
